<template>
  <div class="index">
    <Header></Header>
    <div class="main">
      <p class='current-nav'>当前位置 : <router-link to='index'>首页</router-link> <i> > </i>
        <router-link to='editplan'>应急预案编制</router-link> <i> > </i>应急预案汇编
      </p>

      <div class="infor planmanage2">
        <div class="form-container">
          <p>应急预案汇编</p>
          <div class="manageBtn_div clearfix">
            <el-upload
                action=""
                :http-request="uploadPlan" class="fr"
                >
                    <el-button>
                        <i class="el-icon-upload2">上传</i>
                    </el-button>
            </el-upload>                
            <!-- <el-button>
                <i class="el-icon-upload2">上传</i>
            </el-button> -->
          </div>
        <el-table ref="multipleTable"
                    :data="planList"
                    tooltip-effect="dark"
                     v-loading.lock="loadings"
                     element-loading-spinner="el-icon-loading"
                    @selection-change="handleSelectionChange">
            <el-table-column type="index"
                             align='center'
                             label='序号'
                             width="100">
            </el-table-column>
            <el-table-column prop="planSummaryName"
                             label="应急预案汇编名称"
                              :show-overflow-tooltip="true"
                             align='left'>
            </el-table-column>
            <el-table-column prop="address"
                             label="操作"
                             align='center'
                             width="480">
              <template slot-scope="scope">
                <div class='div-edit'>
                  <el-button v-loading="uploadOver" @click='addpicture(scope.row)' class="newleft" style="margin-left:45px;"><i class="el-icon-edit"></i>添加封面</el-button>
                  <el-button @click='lookstatus(scope.row)' class="newleft"><i class="el-icon-search"></i>查看</el-button>
                  <!--<el-button title="修改或添加封面"><i class="el-icon-edit"></i>修改</el-button>-->

                   <div class="newmsg1">
										  <iframe :src="$baseUrl+'emergency/v1.0/summary/index/'+scope.row.id" width="70" height="40" frameborder="0"></iframe>
									</div>
                  <el-button class="newright" @click="exportplanlist(scope.row);return false;"><i class="el-icon-upload2"></i>导出</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
           <dl>
            <dt class="dl-btn"><i class="el-icon-info"></i>温馨提示</dt>
            <dd>（1）第一次在线编辑文档需安装pageoffice插件，后面无需安装；</dd>
            <dd>（2）如果点击编辑打开失败，请安装 <a href="http://www.wps.cn/" target="_blank">WPS</a> ，即可正常打开；</dd>
            <dd>（3）完整的应急预案汇编包括封面、目录等，请完善封面相关信息，并按照汇编中的目录操作步骤生成目录。</dd>
          </dl>
        </div>
        <el-dialog title="提示"
            :visible.sync="testFlag"
            width="20%"
            :append-to-body="true"
            onselectstart="return false">
            <div class="exampleMain">
              <div class="exampleCon">
                <p style="padding:0;line-height:30px;">试用阶段不可导出应急预案，若想导出，请注册正式账号，相关事项请联系博晟客服 4000270009 转 5</p>
              </div>

              <div class="expoBtn">
                  <a class="submit" @click="testFlag = false">确 定</a>
              </div>
            </div>

          </el-dialog>
      </div>
    </div>
    <Footer />
    
  </div>
</template>

<script>
import Header from '../common/header'
import Footer from '../common/footer'
export default {
  components: {
    Header,
    Footer
  },
  data () {
    return {
testFlag:false,
      dialogVisible: false,
      uploadType: [
        '上传内部应急组织机构', '上传外部应急救援队伍', '上传应急物资装备', '上传应急救援协议'
      ],
      modeType: [
        '内部应急组织机构',
        '外部应急救援队伍',
        '应急物资装备'
      ],
      activeIndex2: -1,
      activeIndex: -1,
      formInline: {
        user: '',
        region: '',
      },

      data1: [{
        c: '1.5M',
        d: '企业管理员',
        flag: false,

        date: '2016-05-02',
        name: '自然灾害',
        address: '现场处置方案'
      }],
      multipleSelection: [],
      currentPage: 1,
      planList:[],
      uploadOver: false
    };
  },
  methods: {
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`);
    },
    onSubmit () {
      console.log('submit!');
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    uploadPlan(fileObj) {
        //导入应急预案
        
        let url =
            this.$baseUrl +
            "emergency/v2.0/upload/plan";
        var fd = new FormData();
        fd.append("file", fileObj.file);
        fd.append(
            "userName",
            JSON.parse(localStorage.getItem("user")).userAccount
        );
        fd.append('companyId',JSON.parse(localStorage.getItem("user")).companyId)
        let config = {
            headers: {
                "Content-Type": "multipart/form-data"
            }
        };
        this.loading = true;
        this.$axios.post(url, fd, config).then(res => {
            this.loading = false;
            if (res.data.meta.success) {
                this.$message({
                    message: "上传成功",
                    type: "success"
                });
                this.getplanlist();
            } else {    
                this.$message.error("上传失败");    
            }
        });
    },
    getplanlist(){
       let params = {
        "companyId": JSON.parse(localStorage.getItem('user')).companyId,
      }
      this.$axios
        ({
          method: 'post',
          url: this.$baseUrl+"emergency/v1.0/summary/plans",
          data: params
        }).then(
          (res) => {
            this.loadings = false;
            this.planList = res.data.data;

          })
    },
    exportplanlist(item){
      var reg=/^[SY_]/g;
      if(JSON.parse(localStorage.user).userAccount.match(reg)){
           this.testFlag=true
      }else{

      this.$axios
        ({
          method: 'get',
          url: this.$baseUrl+"emergency/v1.0/summary/plan/export/"+item.id,
          data: {},
          // responseType:"blob",
        }).then(
          (res) => {
               var timestamp = Date.parse(new Date());
              //   const content = res.data.data
              //    const a = document.createElement('a');
              //    a.download = timestamp;
              //    a.href =;
              //    a.click();
              //    document.body.removeChild(a);
          var browserIsIe = this.browserIsIe();
              // window.location.href = "http://cdns001.bosafe.com/api/v1/file/view/f528284a9dd74e95a2050b0ebf479805.jpg";
                var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
                save_link.href = res.data.data
                save_link.download = timestamp;
                var event = document.createEvent('MouseEvents');
                event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                save_link.dispatchEvent(event);
                return false;

          })


      }
        },
        browserIsIe() {
            if (!!window.ActiveXObject || "ActiveXObject" in window) {
                return true;
            }
            else {
                return false;
        }
    },
     lookmsg(item){
         let url = item.viewUrl;
         var tempwindow=window.open('_blank');//打开一个窗口，然后用

          tempwindow.location=url;//使这个窗口跳转到百度，这样就会呈现弹出百度窗口的效果了。
      },
      addpicture(item){
          if(this.uploadOver){
               this.$message({
                    message: '正在添加封面中，请稍等...',
                    type: 'success'
                });
                return false
          }
        this.uploadOver = true
        let params = {
            "companyId": JSON.parse(localStorage.getItem('user')).companyId,
          }
          this.$axios
            ({
              method: 'post',
              url: this.$baseUrl+"emergency/v1.0/plan/cover",
              data: params
            }).then(
              (res) => {
                  if (res.data.meta.success) {
                    this.$message({
                      message: "添加封面成功",
                      type: 'success'
                    });
                  } else {
                    this.$message({
                      message: res.data.meta.message,
                      type: 'error'
                    });
                  }
                this.uploadOver = false
              })

      },
       lookstatus(item){
          let  baseUrl = item.viewUrl;
          var urlpath = baseUrl.indexOf("?") + 1;
          urlpath = baseUrl.substring(urlpath);
          var arrapi = urlpath.split("&");
          let  uesrMessage = {}
          arrapi.forEach(
              (item)=>{
                  var brrapi = [];
                  brrapi = item.split("=");
                  uesrMessage[brrapi[0]] = brrapi[1];
              }
          )

          let id = uesrMessage.srcFid;
          let  expires = Date.parse(new Date());
          let a = "FastDFS1234Bossien"+id +expires
          console.log(a);
          let token = this.$md5(a)
          token = token.toUpperCase()
          let that = this;
          $.ajax({
              url:this.$baseUrl3+"/queryPublishFileInfo.do?appId=001&srcFid="+id+"&expires="+expires+"&token="+token,
              type:'GET', //GET
              async:false,    //或false,是否异步
              data:{
              },
              timeout:5000,    //超时时间
              success:function(data,textStatus,jqXHR){
                // if()
                let status = JSON.parse(data);
                if(!status.success){
                    that.$message({
                    message: "加载中，请稍后",
                    type: 'error'
                    });
                    return false;
                }
                if(status.dataObj.srcFileStatusName=="12"){
                    that.lookmsg(item)
                }else{
                    that.$message({
                    message: "加载中，请稍后",
                    type: 'error'
                  });
                }
              },
              error:function(xhr,textStatus){
              },
              complete:function(){
              }
          })
          // this.$axios({
          //   method: 'get',
          //   // url:"/queryPublishFileInfo.do?appId=001&scrFid="+id+"&expires="+expires+"&token="+token,
          //   url:"/queryPublishFileInfo.do?appId=001&srcFid="+id+"&expires="+expires+"&token="+token,
          //   data: {}
          // }).then(
          //   (res) => {
          //       // debugger;
          //       let status = JSON.parse(res.data);
          //       if(status.dataObj.srcFileStatusName=="12"){
          //           this.lookmsg(item)
          //       }else{
          //           this.$message({
          //           message: "文件正在转码中，请稍后再查看",
          //           type: 'error'
          //         });
          //       }

          //   }
          // )
      }
  },
  created() {
    this.getplanlist();
    this.loadings = true;
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='less'>
@import "../../../static/css/information.less";

  
.planmanage2 {
    padding-bottom: 200px;
  .form-container {
    padding: 0 0 10px;
    margin: 0 auto;
    p {
      font-size: 16px;
      font-weight: 800;
      color: #666666;
      text-align: center;
      margin: 48px 0 24px 0;
    }
    .manageBtn_div{
        overflow: hidden;
        width: 100%;
        height: 40px;
        padding: 0 100px;
        margin-bottom: 25px;
        .el-button {
            width: 80px;
            background: #f8f7ff;
            border: 0;
            border-radius: 6px;
            margin-right: 4px;
            float: right;
            font-size: 14px;
            color: #6492ff;
        }
        .el-button:hover{
            opacity: .8;
        }
    }
    .el-table {
      width: calc(100% - 200px);
      margin: 0 auto;
      border-top: 1px solid #ebeef5;
      td {
        padding: 0;
        height: 48px;
        line-height: 48px;
      }
      .div-edit {
        .el-button {
          color: #3f80ff;
          background: #f6f9ff;
          border: 0;
          margin: 5px 0 0 10px;
        }
      }
    }
    .page-container {
      width: 620px;
      margin: 50px auto;
      padding: 0;
    }
  }
  dl {
    margin-left: 100px;
    margin-top: 40px;
    font-size: 14px;
    .dl-btn {
      display: inline-block;
      padding: 0 10px;
      height: 36px;
      text-align: center;
      line-height: 36px;
      border-radius: 6px;
      text-align: center;
      margin-bottom: 14px;
    }
    dt.dl-btn {
      background: #f6f9ff;
      color: #3f80ff;
    }
    dd {
      margin-bottom: 10px;
      color: #808080;
      line-height: 36px;
      a{
          color: #30dd05;
          text-decoration: underline;
      }
      span.dl-btn{
          background: #f6f9ff;
          color: #3f80ff;
          padding: 0 20px;
          margin: 0 10px;
      }
    }
  }
  .el-upload-list.el-upload-list--text{
      display: none;
  }
}
.newleft{
  float:left;
}
.newright{
  float: left;
}
.newmsg1{
      float: left;
    margin-top: 3px;
    margin-left: 10px;
}
.expoBtn{
			text-align: right;
			margin-top: 20px;
			.submit{
				display: inline-block;
				border-radius: 8px;
				height: 36px;
				text-align: center;
				line-height: 36px;
				height: 36px;
				width: 85px;
				color: #fff;
				border: none;
				cursor: pointer;
				background: #4080ff;
				background: linear-gradient(left, #6fb2ff 0%, #095fff 100%);
			}
			.submit:hover{
				opacity: .8;
			}
		}
</style>
